package controller

import (
	"ginfast/api/mall/dto"
	"ginfast/api/mall/model"
	"ginfast/pkg/dao"
	"ginfast/pkg/gctx"
	"ginfast/util"

	"github.com/gin-gonic/gin"
)

// Brand 品牌
type Brand struct {
}

// ListHandler 列表
func (o *Brand) ListHandler(c *gin.Context) {
	var p dto.Where
	if err := c.ShouldBind(&p); err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	var data []model.Brand
	total, _ := p.DbModelWhere(&model.Brand{}).Find(&data)
	gctx.JSONWrite(gin.H{"total": total, "rows": data}, c)
}

// GetHandler 查询
func (o *Brand) GetHandler(c *gin.Context) {
	dao.QueryByID(&model.Brand{}, c)
}

// AddHandler 新增
func (o *Brand) AddHandler(c *gin.Context) {
	var p model.Brand
	//获取参数
	if err := c.ShouldBind(&p.BrandOpt); err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	if err := dao.DbCreate(&p); err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	gctx.JSONOK(c)
}

// UpdateHandler 更新
func (o *Brand) UpdateHandler(c *gin.Context) {
	var p model.Brand
	//获取参数
	if err := c.ShouldBind(&p.BrandOpt); err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	if err := dao.DbUpdateModel(&p); err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	gctx.JSONOK(c)
}

type showStatus struct {
	IDS        string `form:"ids"`
	ShowStatus string `form:"showStatus"`
}

func (o *Brand) UpdateShowHandler(c *gin.Context) {
	var p showStatus
	if err := c.ShouldBind(&p); err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	ids := util.StringToIntSlice(p.IDS, ",")
	if err := dao.DbUpdateByIds(&model.Brand{}, ids, dao.H{"show_status": p.ShowStatus}); err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	gctx.JSONOK(c)
}

// UpdateFactoryHandler 更新
func (o *Brand) UpdateFactoryHandler(c *gin.Context) {
	var p model.Brand
	//获取参数
	if err := c.ShouldBind(&p.BrandOpt); err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	if err := dao.DbUpdateColById(&model.Brand{}, p.ID, "factory_status", p.FactoryStatus); err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	gctx.JSONOK(c)
}

// DeleteHandler 删除
func (o *Brand) DeleteHandler(c *gin.Context) {
	dao.Deletes(&model.Brand{}, c)
}

func (o Brand) Routers(r *gin.RouterGroup) {
	r.GET("/list", o.ListHandler)
	r.GET("/:id", o.GetHandler)
	r.POST("", o.AddHandler)
	r.PUT("", o.UpdateHandler)
	r.POST("/showStatus", o.UpdateShowHandler)
	r.POST("/factoryStatus", o.UpdateFactoryHandler)
	r.DELETE("", o.DeleteHandler)
}
